using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Geekeradmin.Common
{
  /// <summary>
  /// 文本设置
  /// </summary>
  public class TextPlainInputFormatter : TextInputFormatter
  {
    /// <summary>
    /// 初始化
    /// </summary>
    public TextPlainInputFormatter()
    {
      SupportedMediaTypes.Add("text/plain");
      SupportedEncodings.Add(UTF8EncodingWithoutBOM);
      SupportedEncodings.Add(UTF16EncodingLittleEndian);
    }

    /// <summary>
    /// 重写
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    protected override bool CanReadType(Type type)
    {
      return type == typeof(string);
    }

    /// <summary>
    /// 重新
    /// </summary>
    /// <param name="context"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public override async Task<InputFormatterResult> ReadRequestBodyAsync(
        InputFormatterContext context,
        Encoding encoding)
    {
      string data = null;
      using (var streamReader = context.ReaderFactory(
          context.HttpContext.Request.Body,
          encoding))
      {
        data = await streamReader.ReadToEndAsync();
      }

      return InputFormatterResult.Success(data);
    }
  }
}
